package controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.view.UrlBasedViewResolver;

public class BaseController {
    /**
     * 转发到任意路径
     */
    public String forward(String url) {
        return UrlBasedViewResolver.FORWARD_URL_PREFIX + url;
    }
    /**
     * 重定向到任意路径
     */
    public String redirect(String url) {
        return UrlBasedViewResolver.REDIRECT_URL_PREFIX + url;
    }
    /**
     * 获取 request 对象
     */
    public HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes()).getRequest();
    }
    /**
     * 设置数据到 request 作用域中
     */
    public void request(String name, Object obj) {
        request().setAttribute(name, obj);
    }
    public <T> T request(String name) {
        return (T) request().getAttribute(name);
    }
    /**
     * 获取 session 对象
     */
    public HttpSession session() {
        return request().getSession();
    }
    /**
     * 设置数据到 session 作用域中
     */
    public void session(String name, Object obj) {
        session().setAttribute(name, obj);
    }
    /**
     * 从 session 作用域中获取数据
     */
    public <T> T session(String name) {
        return (T) session().getAttribute(name);
    }


}
